package com.hengyue.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hengyue.common.core.result.Result;
import com.hengyue.common.core.result.ResultCode;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 响应工具类
 */
@Slf4j
public class ResponseUtils {

    public static void writeErrMsg(HttpServletResponse response, ResultCode resultCode) {
        int status = switch (resultCode) {
            case ACCESS_UNAUTHORIZED,TOKEN_INVALID -> HttpStatus.UNAUTHORIZED.value();
            case TOKEN_ACCESS_FORBIDDEN -> HttpStatus.FORBIDDEN.value();
            default -> HttpStatus.BAD_REQUEST.value();
        };

        response.setStatus(status);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        try(PrintWriter writer = response.getWriter()) {
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = objectMapper.writeValueAsString(Result.failed(resultCode));
            writer.println(jsonString);
            writer.flush();
        } catch (IOException e) {
            log.error("响应异常处理是吧",e);
        }

    }

}
